package com.echovin.esb.gateway.locator;

import com.echovin.esb.gateway.model.GatewayServer;
import com.echovin.esb.gateway.service.GatewayServiceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class GatewayServiceResourceLocator {
    private Map<String, GatewayServer> resourceMap = new ConcurrentHashMap<>();
    @Autowired
    GatewayServiceService gatewayServiceService;

    public GatewayServiceResourceLocator() {
    }

    /**
     * 清空缓存并刷新
     */
    public void refresh() {
        this.resourceMap.clear();
        this.resourceMap.putAll(this.loadResourceDefine());
    }

    /**
     * 服务路径->服务id
     * @param path
     * @return
     */
    public String getServiceId(String path) {
        if (StringUtils.isEmpty(path)) {
            return null;
        }
        GatewayServer gatewayServer = this.resourceMap.get(path);
        if (gatewayServer == null) {
            return null;
        }
        return gatewayServer.getId();
    }

    /**
     * 服务id->服务路径
     * @param serviceId
     * @return
     */
    public String getServicePath(String serviceId) {
        if (StringUtils.isEmpty(serviceId)) {
            return null;
        }
        Iterator<Map.Entry<String, GatewayServer>> entries = this.resourceMap.entrySet().iterator();
        while(entries.hasNext()){
            Map.Entry<String, GatewayServer> entry = entries.next();
            GatewayServer value = entry.getValue();
            if (serviceId.equals(value.getId())) {
                return value.getPath();
            }
        }
        return null;
    }

    /**
     * 调用service查询所有的gateway服务，组装[path：gatewayServer]
     */
    private Map<String, GatewayServer> loadResourceDefine() {
        Map<String, GatewayServer> map = new ConcurrentHashMap<>();
        try {
            List<GatewayServer> resourceList = gatewayServiceService.getGatewayService();
            if (resourceList == null) {
                return map;
            }

            Iterator var3 = resourceList.iterator();
            while(var3.hasNext()) {
                GatewayServer resource = (GatewayServer)var3.next();
                map.put(resource.getPath(), resource);
            }

        } catch (Exception e) {
            log.error("加载gateway服务错误:{}", e);
        }

        log.info("数据库加载服务{}", map.values());

        return map;
    }

}
